﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.IO;
using System.Data;
using App.Core.DB;
using System.Text;

public partial class Pages_Private_CompanyProfileEdit : BasePage
{
    //int _CounntryIDOfBangladesh = ConfigReader.CountryIDOfBangladesh;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropdownLists();
            BindProfileInfo();
        }
    }
    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
    protected void BindDropdownLists()
    {
        BindDropdownList.Countries(ddlCountry);
    }
    protected void BindProfileInfo()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var customer = context.Customers.FirstOrDefault(C => C.ID == SessionCache.CurrentUser.CustomerID);
        txtCompanyName.Text = customer.Name;
        if (!customer.Logo.IsNullOrEmpty())
        {
            imgCompanyLogo.ImageUrl = String.Format("{0}/{1}", AppConstants.CUSTOMER_LOGO, customer.Logo);
            imgCompanyLogo.Visible = true;
        }
        txtAboutUs.Text = customer.About;
        txtWebSite.Text = customer.WebSite;
        ///Bind Addresses
        var addresses = from P in context.Addresses where P.CustomerID == SessionCache.CurrentUser.CustomerID select P;
        if (addresses != null && addresses.Count() > 0)
        {
            List<Address> addressList = addresses.ToList();
            if (addressList.Count == 1)
            {
                BindCompanyAddress(addressList[0]);
                //chkIsBillingAddress.Checked = true;
            }
            else
            {
                Address companyAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == false);
                BindCompanyAddress(companyAddress);
                Address billingAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == true);
                BindBillingAddress(billingAddress);
            }
        }
        ///Bind Contacts
        UtilityDAO dao = new UtilityDAO();
        App.Data.DbParameter[] parameters = new[] { new App.Data.DbParameter("@CustomerID", SessionCache.CurrentUser.CustomerID) };
        DataSet ds = dao.GetDataSet(AppSQL.GET_CUSTOMER_CONTACTS, parameters, false);
        rptContacts.DataSource = ds.Tables[0];
        rptContacts.DataBind();
    }   

    protected void BindCompanyAddress(Address companyAddress)
    {
        //int _CountryID = ddlCountry.SelectedValue.ToInt();

        if ( companyAddress.IsBangladeshi )  // Bangladeshi
        {
            ddlCountry.SetSelectedItem(companyAddress.City.CountryID.ToString());
            ddlCountry_SelectedIndexChanged(ddlCountry, EventArgs.Empty);
            ddlCityID.SetSelectedItem(companyAddress.CityID.ToString());
            cityForBD.Visible = true;
            cityForNonBD.Visible = false; 

        }
        else { // Non Bangladeshi

            ddlCountry.SetSelectedItem(companyAddress.CountryID.ToString());
            //ddlCountry_SelectedIndexChanged(ddlCountry, EventArgs.Empty);
            txtCityName.Text = companyAddress.CityNameForNonBangladeshi;
            cityForBD.Visible = false;
            cityForNonBD.Visible = true; 
        }
        

        BindPhoneNumbers(companyAddress.Phone);
        //txtPhone.Text = companyAddress.Phone;
        txtZipCode.Text = companyAddress.ZipCode;
        txtFax.Text = companyAddress.Fax;
        txtEmail.Text = companyAddress.Email;
        txtStreetAddress.Text = companyAddress.StreetAddress;
    }

    private void BindPhoneNumbers(String phone)
    {
        if (!phone.IsNullOrEmpty())
        {
            String[] phones = phone.Split(',');
            if (phones.Length > 0)
                txtPhone1.Text = phones[0];
            if (phones.Length > 1)
                txtPhone2.Text = phones[1];
            if (phones.Length > 2)
                txtPhone3.Text = phones[2];
        }
    }
    protected String GetCommaSeparatedPhoneNumbers()
    {
        StringBuilder sb = new StringBuilder(10);
        if (!txtPhone1.Text.IsNullOrEmpty())
            sb.AppendFormat(txtPhone1.Text);
        if(!txtPhone2.Text.IsNullOrEmpty())
        {
            if(sb.Length > 0)
                sb.Append(",");
            sb.Append(txtPhone2.Text);
        }
        if (!txtPhone3.Text.IsNullOrEmpty())
        {
            if (sb.Length > 0)
                sb.Append(",");
            sb.Append(txtPhone3.Text);
        }
        return sb.ToString();
    }
    private void BindBillingAddress(Address billingAddress)
    {
        //ddlBillingCountry.SetSelectedItem(billingAddress.City.CountryID.ToString());
        //ddlBillingCountry_SelectedIndexChanged(ddlCountry, EventArgs.Empty);
        //ddlBillingCity.SetSelectedItem(billingAddress.CityID.ToString());
        //txtBillingPhone.Text = billingAddress.Phone;
        //txtBillingZipCode.Text = billingAddress.ZipCode;
        //txtBillingFax.Text = billingAddress.Fax;
        //txtBillingEmail.Text = billingAddress.Email;
        //txtBillingStreetAddress.Text = billingAddress.StreetAddress;
        //chkIsBillingAddress.Checked = false;
    }
    protected void SaveCompanyProfile()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var customer = context.Customers.FirstOrDefault(C => C.ID == SessionCache.CurrentUser.CustomerID);        
        ///Handle Logo Upload
        if (fuLogo.HasFile)
        {
            ///Delete Existing File from FielSystem
            String outputDirectory = Server.MapPath(AppConstants.CUSTOMER_LOGO);
            if (!customer.Logo.IsNullOrEmpty())
            {
                String file = Path.Combine(outputDirectory, customer.Logo);
                if (File.Exists(file))
                    File.Delete(file);
            }
            ///Save new File
            String inputFileName = Server.MapPath(AppConstants.TEMP_DIRECTORY);
            inputFileName = Path.Combine(inputFileName, String.Format("{0}{1}", System.Guid.NewGuid().ToString(), Path.GetExtension(fuLogo.FileName)));
            fuLogo.SaveAs(inputFileName);
            String outputFileName = String.Format("{0}_{1}_Thumb{2}", SessionCache.CurrentUser.CustomerID, Path.GetFileNameWithoutExtension(fuLogo.FileName), Path.GetExtension(fuLogo.FileName));
            outputFileName = Path.Combine(outputDirectory, outputFileName);
            if (!Directory.Exists(outputDirectory))
                Directory.CreateDirectory(outputDirectory);

            WebUtil.GenerateThumbnail(inputFileName, outputFileName, ConfigReader.ThumbnailImageSize, true);
            customer.Logo = Path.GetFileName(outputFileName);
        }
        customer.About = txtAboutUs.Text;
        customer.WebSite = txtWebSite.Text;
        customer.Modified = DateTime.Now;

        ///Save Company Address
        //var address = from P in context.Addresses where P.CustomerID == SessionCache.CurrentUser.CustomerID select P;
        var address = context.Addresses.FirstOrDefault(P => P.CustomerID == SessionCache.CurrentUser.CustomerID);
        int countryID = ddlCountry.SelectedValue.ToInt();
        int countryIDOfBangladesh = ConfigReader.CountryIDOfBangladesh;

        if (address == null)
        {
            address = new Address();
            address.Created = DateTime.Now;      
            customer.Addresses.Add(address);
        }

        if (countryID == countryIDOfBangladesh)
        {
            address.CityID = ddlCityID.SelectedValue.ToInt();
            address.CityNameForNonBangladeshi = null;
            address.IsBangladeshi = true;
            address.CountryID = null;
        }
        else
        {
            address.CountryID = countryID;
            address.CityNameForNonBangladeshi = txtCityName.Text.Trim();
            address.IsBangladeshi = false;
            address.CityID = null;
        }  

        //address.Phone = txtPhone.Text.Trim();
        address.Phone = GetCommaSeparatedPhoneNumbers();
        address.ZipCode = txtZipCode.Text.Trim();
        address.Email = txtEmail.Text;
        address.Fax = txtFax.Text.Trim();
        address.StreetAddress = txtStreetAddress.Text.Trim();
        address.Modified = DateTime.Now;
        address.ModifiedBy = SessionCache.CurrentUser.ID;
        address.IsDeleted = false;
        address.IsBillingAddress = true;

        context.SaveChanges();
        WebUtil.ShowMessageBox(divMessage, "Profile Information Saved Successfully", false);
    }
    //protected void BindPhoneHtml(String phones)
    //{
    //    List<String> allPhones = new List<String>();
    //    if (phones.IsNullOrEmpty())
    //        allPhones.Add(String.Empty);
    //    else
    //    {
    //        String[] numbers = phones.Split(',');
    //        allPhones = numbers.ToList();
    //    }
    //    StringBuilder sb = new StringBuilder(10); 
    //    foreach (String phone in allPhones)
    //    {
    //        sb.AppendFormat("<tr>");
    //    }
    //}
    protected void btnSave_Click(object sendenr, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveCompanyProfile();
            BindProfileInfo();
        }
    }
    protected void cvLogo_ServerValidate(object sender, ServerValidateEventArgs e)
    {     
        if (fuLogo.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuLogo.PostedFile))
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        else
            e.IsValid = true;
    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        int countryID = ddlCountry.SelectedValue.ToInt();
        int countryIDOfBangladesh = ConfigReader.CountryIDOfBangladesh;
        if (countryID == countryIDOfBangladesh)
        {
            BindDropdownList.Cities(ddlCityID, ddlCountry.SelectedValue.ToInt());
            cityForBD.Visible = true;
            cityForNonBD.Visible = false;
        }
        else
        {
            cityForBD.Visible = false;
            cityForNonBD.Visible = true;
        }
    }
    protected String GetPhotoUrl(object fileName)
    {
        String file = NullHandler.GetString(fileName);
        if (!file.IsNullOrEmpty())
        {
            return String.Format("<img class='ContactPhtoto' src='{0}/{1}' alt='{1}' title='{1}'/>", AppConstants.CONTACT_PHOTO, file);
        }
        return String.Empty;
    }
    //protected void ddlBillingCountry_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    BindDropdownList.Cities(ddlBillingCity, ddlBillingCountry.SelectedValue.ToInt());
    //}

    protected void cvCompanyEmail_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        BtcHousingEntities context = new BtcHousingEntities();        
        var addresses = from P in context.Addresses where String.Compare(P.Email, txtEmail.Text, true) == 0 && P.CustomerID != SessionCache.CurrentUser.CustomerID select P;
        if (addresses == null || addresses.Count() == 0)
            e.IsValid = true;
        else
            e.IsValid = false;
    }    
}